package org.geektimes.projects.user.support.messaging;

import org.apache.commons.collections4.CollectionUtils;
import org.geekbang.projects.injection.ApplicationContext;
import org.geekbang.projects.injection.BeanPostProcessor;
import org.geekbang.projects.injection.BeanWrapper;
import org.geekbang.projects.injection.processor.ApplicationContextAware;
import org.geekbang.projects.messaging.StreamContext;
import org.reactivestreams.Subscriber;

import java.util.List;

/**
* messaging处理器  
* @author : lsq
*/
public class MessagingBeanPostProcessor implements BeanPostProcessor , ApplicationContextAware {


	private StreamContext streamContext;

	public static final String MESSAGING_STREAM_CONTEXT =  "messagingStreamContext";

	@Override
	public void initializationBeforePostProcessor(BeanWrapper beanWrapper) {

	}

	@Override
	public void initializationPostProcessor(BeanWrapper beanWrapper) {
		Object bean = beanWrapper.getBean();
		if (bean instanceof Subscriber){
			streamContext.subscribe((Subscriber) bean);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		List<String> beanNamesByType = applicationContext.getBeanNamesByType(StreamContext.class);
		if (!CollectionUtils.isEmpty(beanNamesByType)){
			this.streamContext = applicationContext.getBean(beanNamesByType.get(0));
		}else {
			this.streamContext  = new StreamContext(true);
			applicationContext.registerSingle(MESSAGING_STREAM_CONTEXT , this.streamContext);
		}
	}
}
